/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kom.sound;

import java.util.HashMap;
import java.util.HashSet;
import kom.Kom;
import kuusisto.tinysound.Music;
import kuusisto.tinysound.Sound;
import kuusisto.tinysound.TinySound;

/**
 *
 * @author Nathan
 */
public class Audio {

    private static HashMap<String, Sound> soundCache = new HashMap<String, Sound>();
    private static HashSet<Sound> soundPlayList = new HashSet<Sound>();
    private static HashSet<Sound> soundHasPlayed = new HashSet<Sound>();

    private static final Thread soundThread = new Thread() {
        @Override
        public void run() {
            while (true) {
                if (soundPlayList.size() > 0) {
                    for (Sound s : soundPlayList) {
                        s.play(0.5);
                        soundHasPlayed.add(s);
                    }
                    if (soundHasPlayed.size() > 0) {
                        soundPlayList.removeAll(soundHasPlayed);
                        soundHasPlayed.clear();
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
    };
    
    static {
        soundThread.start();
        TinySound.init();
    }

    public static void playSound(final String name) {
        if (soundCache.containsKey(name)) {
            Sound s = soundCache.get(name);
            soundPlayList.add(s);
        } else {
            Sound s = TinySound.loadSound(Kom.class.getResource("/res/sounds/" + name + ".wav"));
            soundCache.put(name, s);
            soundPlayList.add(s);
        }
    }

    public static void loopMusic(final String path) {
        try {
            new Thread() {
                @Override
                public void run() {
                    TinySound.init();
                    Music music = TinySound.loadMusic("resource/sounds/" + path + ".wav");
                    music.play(true);
                }
            }.start();
        } catch (Throwable e) {
            e.printStackTrace(System.out);
        }
        TinySound.shutdown();
    }
}
